from django.http import JsonResponse
# Create your views here.

from django.db import connection
from django.views.decorators.http import require_http_methods
from .models import AdministrativeList


@require_http_methods(['GET'])
def getListByLevel(request):
    # 获取level的值
    level = request.GET.get('level', None)
    if level is not None:
        try:
            level = int(level)
        except ValueError:
            return JsonResponse({'error': 'Level must be an integer.'}, status=500)

        administrative_list = AdministrativeList.objects.filter(level=level)

        data = list(administrative_list.values())  # 这会获取模型的所有字段
        # 将QuerySet转换为列表字典形式
        # data = list(administrative_list.values('gid', 'code', 'level', 'name'))
        print(data)
        return JsonResponse({'datas': data}, status=200)
    else:
        return JsonResponse({'error': 'Parameter level is required.'}, status=500)



@require_http_methods(['GET'])
def getNextList(request):
    """
    根据当前的level和code查询下一级的list

    level:当前层级

    code:当前code
    """
    level = request.GET.get('level', None)
    code = request.GET.get('code', None)
    if level is not None and code is not None:
        try:
            level = int(level)
        except ValueError:
            return JsonResponse({'error': 'Level must be an integer.'}, status=500)
        # 实例化游标对象
        cursor = connection.cursor()
        cursor.execute("select * from administrative_list where level=%s and city_code=%s", [level+1, code])
        data = cursor.fetchall()
        print(data)
        return JsonResponse({'datas': data}, status=200)
    else:
        return JsonResponse({'error': 'level和code不能为空'}, status=500)